package com.weichat.accessToken;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import org.json.JSONException;
import org.json.JSONObject;

public class GetAccessToken {
	private static final String access_token_url="https://api.weixin.qq.com/cgi-bin/token?"
            + "grant_type=client_credential&appid=APPID&secret=APPSECRET";

/**
     * 获取Access_Token
     * @param appid
     * @param appsecret
     * @return
 * @throws IOException 
     */
    public static AccessToken getAccessToken(String appid,String appsecret) throws IOException{
        AccessToken accessToken=null;
        String requestUrl=access_token_url.replace("APPID",appid).replace("APPSECRET", appsecret);
        URL url2=new URL(requestUrl);
		HttpsURLConnection con=(HttpsURLConnection) url2.openConnection();
		con.setRequestMethod("GET");
		con.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); 
		con.setDoOutput(true); 
		con.setDoInput(true);
		
		con.connect();
		InputStream input=con.getInputStream();
		byte[] c=new byte[input.available()];
		input.read(c);
		// String有一个构造方法，可以接受一个，字节的数组，来创建一个String.
		//这个过程，就实现了，字节数组转化为String的过程。
		String message=new String(c,"UTF-8");
		input.close();
		con.disconnect();
		
		JSONObject demoJson;
		try {
			demoJson = new JSONObject(message);
			accessToken=new AccessToken();
			accessToken.setToken(demoJson.getString("access_token"));
			accessToken.setExpiresIn(demoJson.getInt("expires_in"));
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return accessToken;
    }

}
